<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot="menu" slot-scope="{ row }">
        <el-button icon="el-icon-view" size="small" type="text" @click="viewSequenceNumber(row)"> 查看包装</el-button>
        <el-button type="text" @click="viewReport(row)" icon="el-icon-view" size="small" v-if="permission.iqcInspectionReport_viewReport">查看检验报告</el-button>
      </template>
      <template slot="menuLeft">
        <el-button type="warning" size="small" icon="el-icon-download" @click="$refs.exportComp.visible = true" v-if="permission.iqcInspectionReport_export">导出</el-button>
      </template>
      <template slot-scope="{ row }" slot="disposeType">
        <span> {{ getDisposeType(row.disposeType) }}</span>
      </template>
      <!-- <template slot-scope="{ row }" slot="returnQuantity">
        <span> {{ row.disposeType === 'EXTRACTION' ? row.sendExamineQuantity - row.disposeQuantity : row.disposeType === 'FULLRETURN' ? row.returnQuantity : 0 }}</span>
      </template>
      <template slot-scope="{ row }" slot="extractionQuantity">
        <span>{{ row.examineResult === 'NG' ? row.extractionQuantity : 0 }}</span>
      </template> -->
      <!-- <template slot-scope="{ row }" slot="actualQuantity">
        <span> {{ row.examineResult === 'OK' ? row.sendExamineQuantity : row.disposeQuantity }}</span>
      </template> -->
    </avue-crud>
    <el-dialog ref="dialog" title="包装详情" class="lookPackDialog" append-to-body :visible.sync="showSequenceNumberDialog" :close-on-click-modal="false">
      <avue-crud :option="sequenceNumberOption" :row-class-name="tableRowClassName" :table-loading="sequenceNumberLoading" :data="sequenceNumberData" ref="crud">
        <template slot="menuLeft">
          <el-button type="text" style="color: red">*注：红色字体的包装条码为IQC检验时的不良包装条码</el-button>
        </template>
      </avue-crud>
    </el-dialog>
    <el-dialog class="sequence-number-dialog" append-to-body :visible.sync="showViewDialog" width="40%" :fullscreen="fullscreenDialog" @click="cancelView">
      <div slot="title">
        查看<i class="el-dialog__close fill-screen-icon" :class="fullscreenDialog ? 'el-icon-news' : 'el-icon-full-screen'" @click="fullscreenDialog = !fullscreenDialog"></i>
      </div>
      <avue-form ref="properties" v-model="viewModel" :option="viewOption">
        <!-- <template slot="examineResultLabel">
          <span class="view-style">&nbsp;IQC检验结果:</span>
        </template> -->

        <template slot="inspectionAttachments">
          <div>
            <!-- <div>
              <span class="view-style">&nbsp;IQC检验报告:</span>
            </div> -->
            <div style="display: inline-block; text-align: center" v-for="(item, index) in iqcInspectionAttachments" :key="item.attachmentId">
              <el-image style="width: 100px; height: 100px; padding-right: 10px; display: block" :src="item.link" @click="openPreview(index, item.link)"></el-image>
              <el-button type="text" v-if="item.link" icon="el-icon-download" size="small" @click="handleDownload(item)">下载 </el-button>
            </div>
          </div>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </template>
        <!-- <template slot="remarkLabel">
          <span>&nbsp;备注:</span>
        </template> -->

        <template slot="badHandling">
          <span class="view-style">&nbsp;不良处理</span>
        </template>

        <template slot="inspectionNGAttachments">
          <div>
            <!-- <div>
              <span >&nbsp;不良照片</span>
            </div> -->
            <div style="display: inline-block; text-align: center" v-for="(item, index) in iqcNGAttachments" :key="item.attachmentId">
              <el-image style="width: 100px; height: 100px; padding-right: 10px; display: block" :src="item.link" @click="openPreview(index, item.link)"></el-image>
              <el-button type="text" v-if="item.link" icon="el-icon-download" size="small" @click="handleDownload(item)">下载 </el-button>
            </div>
          </div>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </template>
        <template slot="disposeType">
          <div>
            <el-input disabled v-model="disposeTypeLabel"></el-input>
          </div>
        </template>
      </avue-form>
    </el-dialog>
    <export-comp ref="exportComp" page-api-url="mes-product/inspection-document/page" :option="option" :page="page" :query="query" file-name="IQC检验报表"> </export-comp>
  </basic-container>
</template>

<script>
import { getList, getDetail } from '@/api/quality/iqc-examine';
import { mapGetters } from 'vuex';
import exportExcel from '@/components/export-excel';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
import exportComp from '@/components/export-comp';
import { getList as getAttributeConfigList } from '@/api/system/custom-attribute-config';
export default {
  components: {
    exportComp,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'IQC_INSPECTION_REPORT',
      showSequenceNumberDialog: false,
      exportData: [],
      form: {},
      model: {},
      query: { statusStr: '2,3' },
      viewModel: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      disposeTypeLabel: '',
      iqcInspectionAttachments: [],
      iqcNGAttachments: [],
      selectionList: [],
      sequenceNumberData: [],
      data: [],
      selectData: [],
      code: '00',
      searchLabelWidth: 100,
      checkIqc: true,
      sequenceNumberLoading: false,
      sequenceNumberOption: {
        height: 'calc(100vh - 350px)',
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        selection: false,
        dialogClickModal: false,
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        delBtn: false,
        menu: false,
        refreshBtn: false,
        columnBtn: false,
        column: [
          {
            label: '包装条码',
            prop: 'sequenceNumber'
          },
          {
            label: '数量',
            prop: 'quantity'
          },
          {
            label: '是否尾箱',
            prop: 'isTailBox',
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ]
          },
          {
            label: '状态',
            prop: 'packStatus',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=pack_status',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicFormatter: (res) => {
              this._forEach(res.data, (item) => {
                item.dictKey = Number(item.dictKey);
              });
              return res.data;
            }
          },
          {
            label: '不良原因',
            prop: 'failureNameList'
          },
          {
            label: '处理方案',
            prop: 'disposeType',
            type: 'select',
            dicData: [
              {
                label: '批量退货',
                value: 'FULLRETURN'
              },
              {
                label: '让步收料',
                value: 'DEVIATION'
              },
              {
                label: '部分特采',
                value: 'EXTRACTION'
              }
            ]
          }
        ]
      },
      option: {
        columnBtn: false,
        height: 'calc(100vh - 485px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 18,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        addBtn: false,
        delBtn: false,
        editBtn: false,
        selection: true,
        dialogClickModal: false,
        labelWidth: 120,
        menuWidth: 100,
        searchLabelWidth: 90,
        searchMenuPosition: 'right',
        menuWidth: 200,
        column: [
          {
            label: '检验单号',
            prop: 'documentNo',
            search: true,
            searchOrder: 4,
            rules: [
              {
                required: true,
                message: '请输入检验单号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '检验方式',
            prop: 'examineMode',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=inspection_mode',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: true,
                message: '请输入检验方式',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '物料编码',
            prop: 'partNo',
            searchOrder: 1,
            search: true,
            rules: [
              {
                required: true,
                message: '请输入物料编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '客户料号',
            hide: true,
            prop: 'customerPartNumber',
            rules: [
              {
                required: true,
                message: '请输入物料名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '物料名称',
            prop: 'partName',
            searchOrder: 2,
            search: true,
            rules: [
              {
                required: true,
                message: '请输入物料名称',
                trigger: 'blur'
              }
            ]
          },
          // {
          //   label: '物料批次',
          //   prop: 'lotNo',
          //   rules: [
          //     {
          //       required: true,
          //       message: '请输入物料批次',
          //       trigger: 'blur'
          //     }
          //   ]
          // },
          {
            label: '物料规格',
            prop: 'partModel',
            rules: [
              {
                required: true,
                message: '请输入物料规格',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '送检数量',
            prop: 'sendExamineQuantity',
            rules: [
              {
                required: true,
                message: '请输入送检数量',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '检验数量',
            prop: 'examineQuantity'
          },
          {
            label: '检验结果',
            prop: 'examineResult',
            searchOrder: 5,
            dicUrl: '/api/blade-system/dict/dictionary?code=examineResult',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            search: true,
            type: 'select',
            rules: [
              {
                required: true,
                message: '请输入检验结果',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '不良处理方式',
            prop: 'disposeType',
            rules: [
              {
                required: true,
                message: '请输入不良处理方式',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '退货数量',
            prop: 'returnQuantity'
          },
          {
            label: '特采数量',
            prop: 'extractionQuantity',
            rules: [
              {
                required: true,
                message: '请输入特采数量',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '实收数量',
            prop: 'realityQuantity'
          },
          {
            label: '采购单号',
            prop: 'sheetNo',
            searchOrder: 6,
            search: true,
            rules: [
              {
                required: true,
                message: '请输入采购单号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '制单人',
            prop: 'creator'
          },
          {
            label: '供应商代码',
            prop: 'partnerCode',
            searchOrder: 3,
            search: true,
            rules: [
              {
                required: true,
                message: '请输入供应商代码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '供应商名称',
            searchOrder: 5,
            prop: 'partnerName',
            rules: [
              {
                required: true,
                message: '请输入供应商名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '送检日期',
            prop: 'sendExamineDate',
            type: 'date',
            searchType: 'daterange',
            format: 'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
          },
          {
            label: '检验日期',
            prop: 'examineDate',
            search: true,
            searchOrder: 7,
            searchSpan: 6,
            type: 'date',
            searchType: 'daterange',
            format: 'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
          },
          {
            label: '检验人员',
            prop: 'examineByName',
            search: true,
            searchOrder: 8
          }
        ]
      },
      showViewDialog: false,
      fullscreenDialog: false,
      viewOption: {
        emptyBtn: false,
        submitBtn: false,
        labelWidth: '80',
        menuPosition: 'left',
        labelPosition: 'left',
        column: [
          {
            label: 'IQC检验结果',
            labelslot: true,
            prop: 'examineResult',
            type: 'input',
            disabled: true,
            labelWidth: '100',
            control: (val, form) => {
              if (val == 'OK') {
                return {
                  examineBy: { display: false },
                  examineDate: { display: false },
                  disposeType: { display: false },
                  sendExamineQuantity: { display: false },
                  returnQuantity: { display: false },
                  extractionQuantity: { display: false },
                  actualQuantity: { display: false },
                  badHandling: { display: false },
                  inspectionNGAttachments: { display: false },
                  disposeRemark: { display: false }
                };
              } else {
                return {
                  examineBy: { display: true },
                  examineDate: { display: true },
                  disposeType: { display: true },
                  sendExamineQuantity: { display: true },
                  returnQuantity: { display: true },
                  extractionQuantity: { display: true },
                  actualQuantity: { display: true },
                  badHandling: { display: true },
                  inspectionNGAttachments: { display: true },
                  disposeRemark: { display: true }
                };
              }
            }
          },

          {
            label: 'IQC检验报告',
            prop: 'inspectionAttachments',
            // type: 'img',
            labelWidth: '100',

            span: 24,
            require: true,
            formslot: true
          },
          {
            label: '备注/原因',
            prop: 'remark',
            span: 24,
            type: 'textarea',
            labelWidth: '100',

            maxRows: 3,
            minRows: 3,
            disabled: true
          },
          {
            label: '',
            disabled: true,
            labelWidth: 0,
            prop: 'badHandling',
            span: 24
          },
          {
            label: '处理人员',
            disabled: true,
            prop: 'examineBy',
            span: 8
          },
          {
            label: '处理时间',
            disabled: true,
            prop: 'examineDate',
            span: 8
          },
          {
            label: '处理类型',
            disabled: true,
            prop: 'disposeType',
            span: 8,
            dicData: [
              { label: '部分特采', value: 'EXTRACTION' },
              { label: '让步收料', value: 'DEVIATION' },
              { label: '批量退货', value: 'FULLRETURN' },
              { label: '正常', value: 'NORMAL' }
            ]
          },
          {
            label: '送检数量',
            disabled: true,
            prop: 'sendExamineQuantity',
            span: 8
          },
          {
            label: '退货数量',
            disabled: true,
            prop: 'returnQuantity',
            span: 8
          },
          {
            label: '特采数量',
            disabled: true,
            prop: 'extractionQuantity',
            span: 8
          },
          {
            label: '实收数量',
            disabled: true,
            prop: 'realityQuantity',
            span: 8
          },
          {
            label: '不良照片',
            labelWidth: '100',
            span: 24,
            prop: 'inspectionNGAttachments',
            require: true,
            formslot: true
          },
          {
            label: '备注/原因',
            prop: 'disposeRemark',
            labelWidth: '100',
            span: 24,
            type: 'textarea',
            maxRows: 3,
            minRows: 3,
            disabled: true
          }
        ]
      },
      customAttributeList: [] //扩展属性
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.location_view, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  created() {
    let path = this.$route.path;
    getAttributeConfigList(path).then((res) => {
      this.customAttributeList = this._get(res, 'data.data', []);
      this._forEach(this.customAttributeList, (item, index) => {
        this.option.column.splice(1 + index, 0, {
          label: item.lableCnName,
          prop: item.attributeKey,
          type: item.controlType,
          value: item.defaultValue,
          dispaly: item.enabled,
          search: true,
          searchOrder: 9
        });
      });
      this.$refs.crud.refreshTable();
    });
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    getDisposeType(key) {
      switch (key) {
        case 'EXTRACTION':
          return '部分特采';
        case 'DEVIATION':
          return '让步收料';
        case 'FULLRETURN':
          return '批量退货';
        case 'NORMAL':
          return '正常';
        default:
          return '';
      }
    },
    cancel() {
      this.showDialog = false;
    },

    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = { statusStr: '2,3' };
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.examineDate && params.examineDate.length > 0) {
        params.startExamineDate = params.examineDate[0];
        params.endExamineDate = params.examineDate[1];
        // let startExamineDate = new Date(params.examineDate[0]);
        // startExamineDate.setHours(0, 0, 0);
        // let endExamineDate = new Date(params.examineDate[1]);
        // endExamineDate.setHours(23, 59, 59);
        // params.startExamineDate = this.$moment(startExamineDate).format('YYYY-MM-DD  HH:mm:ss');
        // params.endExamineDate = this.$moment(endExamineDate).format('YYYY-MM-DD  HH:mm:ss');
      }
      delete params.examineDate;
      params.statusStr = '2,3';
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      params.documentType = 'IQC';
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query, { descs: 'create_time' })).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this._forEach(data.records, (item) => {
          if (!item.returnQuantity) {
            item.returnQuantity = 0;
          }
          if (!item.extractionQuantity) {
            item.extractionQuantity = 0;
          }
          if (!item.realityQuantity) {
            item.realityQuantity = 0;
          }
        });
        // [] || dataListTable
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    // 修改查看检验报告方式 启用原PC view()方式, 采用Ureport方式
    viewReport(row) {
      let reportTemplateName = this._get(row, 'inspectionTemplate.reportTemplateName', '');
      window.open(`${this.website.reportUrl}/preview?_u=blade-${reportTemplateName}&qcId=${row.id}`);
    },
    viewSequenceNumber(row) {
      this.showSequenceNumberDialog = true;
      this.sequenceNumberLoading = true;
      getDetail(row.id).then((res) => {
        let data = res.data.data;
        this.sequenceNumberData = this._map(data.receivingVOList, (item) => {
          if (item.disposeType === 'NORMAL') {
            item.disposeType = '';
          }
          item.failureNameList = item.failureNameList ? item.failureNameList.join(',') : '';
          return item;
        });
        console.log(this.sequenceNumberData, 33344);
        this.sequenceNumberLoading = false;
      });
    },
    tableRowClassName({ row, rowIndex }) {
      let className = row.isNg ? 'font-color-style' : '';
      return className;
    },
    async view(id) {
      this.viewModel = {};
      this.showViewDialog = true;
      this.fullscreenDialog = false;
      getDetail(id).then((res) => {
        this.viewModel = res.data.data;
        this.iqcInspectionAttachments = [];
        this.iqcNGAttachments = [];
        this.disposeTypeLabel = this.getDisposeType(this.viewModel.disposeType);
        this.viewModel.actualQuantity = this.viewModel.disposeQuantity;
        if (this.viewModel.disposeType === 'EXTRACTION') {
          this.viewModel.returnQuantity = '';
          this.viewModel.extractionQuantity = this.viewModel.disposeQuantity;
        } else {
          this.viewModel.returnQuantity = this.viewModel.sendExamineQuantity;
          this.viewModel.extractionQuantity = '';
        }
        (this.viewModel.attachments || []).map((attachment) => {
          if (attachment.attachmentType === 'NG') {
            this.iqcNGAttachments.push(attachment);
          } else {
            this.iqcInspectionAttachments.push(attachment);
          }
        });
      });
    },
    cancelView() {
      this.showViewDialog = false;
      this.viewModel = {};
      this.iqcInspectionAttachments = [];
      this.iqcNGAttachments = [];
    },
    handleDownload(item) {
      window.open(`${item.link}`);
    },

    openPreview(index = 0, link) {
      this.$ImagePreview([{ url: link }], index, {
        closeOnClickModal: false
      });
    }
  }
};
</script>

<style scoped lang="scss">
$size: 16px;
.view-style {
  font-weight: bold;
  font-size: $size;
}
$BORDER-STYLE: 1px solid #f0f0f0 !important;
::v-deep .inspection-btn:hover {
  background-color: #dedede;
}
::v-deep .el-dialog__header {
  border-bottom: $BORDER-STYLE;
}

::v-deep .el-dialog__footer {
  border-top: $BORDER-STYLE;
}

.fill-screen-icon {
  color: #909399;
  font-size: 15px;
  float: right;
  padding-right: 25px;
  &:hover {
    color: #409eff;
  }
}

.group-title {
  border-bottom: 1px solid rgb(240, 240, 240) !important;
  font-size: 16px;
  font-weight: 500;
  height: 50px;
  line-height: 50px;
  color: rgba(0, 0, 0, 0.85);
  margin-bottom: 20px;
}
::v-deep .el-table .font-color-style {
  color: red;
}
</style>
